/**
 *  用例 :
 *  var hws = new HylWSocket("localhost:8080/hjsp/ws/a/1", function(e) {
      console.log(e)
    })
 */
(function(e, t) {
 if ("object" == typeof exports && "object" == typeof module) module.exports.HylWSocket = t;
 else if ("function" == typeof define && define.amd) define(t);
 else e.HylWSocket = t; //静态函数库
})(this, function(serverurl, onReceiveMsg, onOpen, onClose) {
    var that = this;
    that.socket = null;
    that.messageNum = 0;//收到消息数
    that.socketConnectedEnable = true;
    that._onReceiveMsg = onReceiveMsg;
    that._onOpen = onOpen;
    that._onClose = onClose;
    that._url = "ws://" + serverurl;
    //console.log(that._url, serverurl)
    that.connect= function () {
      if ('WebSocket' in window) {
        that.socket = new window.WebSocket(that._url);
      } else {
        if ('MozWebSocket' in window) {
          that.socket = new window.MozWebSocket(that._url);
        } else {
          console.log('当前浏览器 不支持 websocket')
          return;
        }
      }
      //收到消息
      that.socket.onmessage = function(event) {
        that.messageNum++
        if (that._onReceiveMsg)
          that._onReceiveMsg(event, that);
      };
      //连接成功
      that.socket.onopen = function(event) {
        if (that._onOpen)
          that._onOpen(event);
        console.log("连接开启!")
      };
      //连接成功
      that.socket.onclose = function(event) {
        if (that._onClose)
          that._onClose(event);
        console.log("连接关闭!")
      };
    }
    that.send = function(message) {
      if (that.socket&&that.socket.readyState==1) {
        that.socket.send(message);
      } else{
        that.socket=null
        console.log("连接已经关闭,重新连接");
        setTimeout(that.connect, 1000);
      }
    }
    //保持连接的方式 每隔100s  ping一下主机 如果断开重连
    that.timer = setInterval(function() {
      if (that.socketConnectedEnable) {
        //console.log("ping");
        that.send("hi");
      }
    }, 180000);
    //
    that.close = function() {
    	  console.log("关闭??")
      clearTimeout(that.timer);
      that.socket.close();
    }
    that.connect()
});